﻿<%@ WebHandler Language="C#" Class="LingLiaoSendBackTimesReport" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Net;
using ReportBusiness;

/**
 * Description: 领料单退回次数统计报表
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2022.4.15
 **/

public class LingLiaoSendBackTimesReport : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getSearchSqlString(JObject jObject)
    {
        string sql = @"
SELECT te.factoryname,cci.productname,cci.productdescription,ua.attributevalue clph,te.containername,cci.qty,e.fullname startPerson,
        e2.fullname techPerson,ua2.attributevalue sfs,ua3.attributevalue jybh,ua4.attributevalue lpc,te.wzjhy,te.sendBackType,te.times,
        te2.totalTimes
FROM
(
    SELECT f.factoryname,e.fullname wzjhy,substr(nv.notes,INSTR(nv.notes,':')+1) sendBackType,c.containername,c.containerid,COUNT(nv.notes) -1 times
    FROM MOVEHISTORY nv 
    LEFT JOIN employee e ON e.employeeid=nv.reportemployeeid
    LEFT JOIN workflowstep ws ON ws.workflowstepid=nv.stepid
    LEFT JOIN workflowstep ws2 ON ws2.workflowstepid=nv.tostepid
    LEFT JOIN containercurrentinfo c ON c.containerid=nv.historyid
    LEFT JOIN factory f ON f.factoryid = c.originalfactoryid
    LEFT JOIN Userattribute ut ON ut.parentid=c.containerid AND ut.userattributename='代料单号' AND nv.notes LIKE '%代料重审%'
    WHERE ws.sequence=2 AND ws2.workflowstepname='工艺确认'  AND nv.changecount=1 AND nv.notes LIKE '物资退回:%'  
";
        //分厂
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND c.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        //零件图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND c.productname = '{0}'", jObject["productname"].ToString());
        }

        //流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND c.containername = '{0}'", jObject["containername"].ToString());
        }

        sql += @"
GROUP BY f.factoryname,e.fullname,nv.notes,c.containername,c.containerid
) te
LEFT JOIN (
SELECT f.factoryname,c.containername,c.containerid,COUNT(nv.notes) totalTimes
                    FROM MOVEHISTORY nv
                    LEFT JOIN workflowstep ws ON ws.workflowstepid=nv.stepid
                    LEFT JOIN workflowstep ws2 ON ws2.workflowstepid=nv.tostepid
                    LEFT JOIN containercurrentinfo c ON c.containerid=nv.historyid
                    LEFT JOIN factory f ON f.factoryid = c.originalfactoryid
                    LEFT JOIN Userattribute ut ON ut.parentid=c.containerid AND ut.userattributename='代料单号' AND nv.notes LIKE '%代料重审%'
                    WHERE ws.sequence=2 AND ws2.workflowstepname='工艺确认'  AND nv.changecount=1 AND nv.notes LIKE '物资退回:%'
";
        //分厂
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND c.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        //零件图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND c.productname = '{0}'", jObject["productname"].ToString());
        }

        //流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND c.containername = '{0}'", jObject["containername"].ToString());
        }

        sql += @"
GROUP BY f.factoryname,c.containername,c.containerid
) te2 ON te2.containerid = te.containerid
LEFT JOIN containercurrentinfo cci ON cci.containerid = te.containerid
                    LEFT JOIN Userattribute ua ON ua.parentid = cci.containerid AND ua.attributevalue = '材料牌号'
                    LEFT JOIN container c ON c.containerid = cci.containerid
                    LEFT JOIN employee e ON e.employeeid = c.startemployeeid
                    LEFT JOIN employee e2 ON e2.employeeid = cci.techniqueemployeeid
                    LEFT JOIN Userattribute ua2 ON ua.parentid = cci.containerid AND ua.attributevalue = '实发数'
                    LEFT JOIN Userattribute ua3 ON ua.parentid = cci.containerid AND ua.attributevalue = '检验编号'
                    LEFT JOIN Userattribute ua4 ON ua.parentid = cci.containerid AND ua.attributevalue = '熔炉号母'
";

        return sql;
    }

    //查询方法
    Result getData(JObject jObject)
    {
        Result r = new Result();

        string sql = getSearchSqlString(jObject);

        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);

        DataTable dt = dto.DBTable;

        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = getSearchSqlString(jObject);
        DataTable dtResult = dal.GetDataTable(sql);

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        dtResult.Columns["factoryname"].Caption = "分厂";
        dtResult.Columns["productname"].Caption = "件号";
        dtResult.Columns["productdescription"].Caption = "名称";
        dtResult.Columns["clph"].Caption = "材料牌号";
        dtResult.Columns["containername"].Caption = "流水卡号";
        dtResult.Columns["qty"].Caption = "订单数量";
        dtResult.Columns["startperson"].Caption = "计划员";
        dtResult.Columns["techperson"].Caption = "工艺员";
        dtResult.Columns["sfs"].Caption = "实发数";
        dtResult.Columns["jybh"].Caption = "检验编号";
        dtResult.Columns["lpc"].Caption = "炉批次";
        dtResult.Columns["wzjhy"].Caption = "计划员";
        dtResult.Columns["sendbacktype"].Caption = "错误类型";
        dtResult.Columns["times"].Caption = "重复次数";
        dtResult.Columns["totaltimes"].Caption = "退回次数";

        ExportHelper.ExportExcel(dtResult, "领料单退回次数统计报表");
    }
}